//
//  CommunityBigImageViewController.m
//  1gene
//
//  Created by 1jiyin on 16/3/14.
//  Copyright © 2016年 1jiyin. All rights reserved.
//

#import "CommunityBigImageViewController.h"

@interface CommunityBigImageViewController ()<UIScrollViewDelegate>

@property(nonatomic,copy)UILabel *titleLab;


@end

@implementation CommunityBigImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:[UIView new]];
    [self createNavigation];
    [self createUI];
    // Do any additional setup after loading the view.
}

-(void)createNavigation
{
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    //返回上一页
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 0, 25, 25);
    [btn setBackgroundImage:[UIImage imageNamed:@"left_back"] forState:UIControlStateNormal];
    //    [btn setTitle:@"返回" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:btn];
    
    //下载
    UIButton *downloadBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    downloadBtn.frame=CGRectMake(0, 0, 25, 25);
    [downloadBtn setBackgroundImage:[UIImage imageNamed:@"shequ_image_download"] forState:UIControlStateNormal];
    //    [btn setTitle:@"返回" forState:UIControlStateNormal];
    [downloadBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [downloadBtn addTarget:self action:@selector(downloadBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:downloadBtn];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:downloadBtn];
    
    _titleLab=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    _titleLab.text=[NSString stringWithFormat:@"%ld/%ld",_currentIndex+1,_imageArrays.count];
    _titleLab.font=[UIFont systemFontOfSize:22];
    _titleLab.textColor=[UIColor whiteColor];
    _titleLab.textAlignment=NSTextAlignmentCenter;
    self.navigationItem.titleView=_titleLab;
}





-(void)createUI
{
    NSLog(@"传过来的下标====%ld===%ld",_currentIndex,_imageArrays.count);
    
    UIScrollView *scroll=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    scroll.showsHorizontalScrollIndicator=NO;
    scroll.pagingEnabled=YES;
    scroll.delegate=self;
    [self.view addSubview:scroll];
    scroll.contentSize=CGSizeMake(scroll.frame.size.width*_imageArrays.count, scroll.frame.size.height);
    
    for (int i=0; i<_imageArrays.count; i++) {
        UIView *subView=[[UIView alloc]initWithFrame:CGRectMake(i*scroll.frame.size.width, 0, scroll.frame.size.width, scroll.frame.size.height)];
        [scroll addSubview:subView];
        NSLog(@"横坐标====%f",subView.frame.origin.x);
        UIImageView *imgView=[[UIImageView alloc]init];
        NSString *urlStr=_imageArrays[i];
        urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]];
        imgView.image=image;
        imgView.frame=CGRectMake(0, 0, image.size.width, image.size.height);
        if (image.size.width>=self.view.frame.size.width) {
            imgView.frame=CGRectMake(0, 0, self.view.frame.size.width, image.size.height/((image.size.width/(self.view.frame.size.width*1.0))*1.0));
        }
        
        imgView.center=CGPointMake(subView.frame.size.width/2.0, subView.frame.size.height/2.0);
        [subView addSubview:imgView];

    }
    scroll.contentOffset=CGPointMake(scroll.frame.size.width*_currentIndex, 0);
    
    
    
    
    
    //self.navigationController.navigationBar.hidden=YES;
}
//scrollView的代理
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _currentIndex=scrollView.contentOffset.x/scrollView.frame.size.width;
    NSLog(@"");
    _titleLab.text=[NSString stringWithFormat:@"%ld/%ld",_currentIndex+1,_imageArrays.count];
}








-(NSString*)documentsDirectory{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths firstObject];
    return documentsDirectory;
}
///Users/1jiyin/Library/Developer/CoreSimulator/Devices/A9A97531-981E-496F-BE5A-0733C024B477/data/Containers/Data/Application/52A63004-4DAE-4CA5-AD01-1E8D5D473C23/Documents/img
//下载
-(void)downloadBtnClick:(UIButton *)sender
{
    [self downLoadImage];
//    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//    NSURL *URL = [NSURL URLWithString:@"http://img01.liwushuo.com/image/150310/62ggu1j0m.png-pw144"];
//    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//    //NSLog(@"图片地址：%@",request);
//    //UIApplication *app = [UIApplication sharedApplication];
//    ////app.networkActivityIndicatorVisible =YES;//转动
//    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
//                                              {
//                                                  NSString *documentsDirectory=[self documentsDirectory];
//                                                  NSString *filenamepath=[documentsDirectory stringByAppendingPathComponent:@"img/"];
//                                                  NSLog(@"=========%@",filenamepath);
//                                                  NSFileManager *fileManager = [NSFileManager defaultManager];
//                                                  if([fileManager fileExistsAtPath:filenamepath])//检查文件夹是否存在
//                                                  {//文件夹存在
//                                                      //NSLog(@"文件夹存在");
//                                                  }
//                                                  else
//                                                  {//文件夹不存在
//                                                      //NSLog(@"文件夹不存在");
//                                                      //创建路径
//                                                      [fileManager createDirectoryAtPath:filenamepath withIntermediateDirectories:YES attributes:nil error:nil];
//                                                  }
//                                                  NSURL *documentsDirectoryPath=[NSURL fileURLWithPath:filenamepath];
//                                                  //返回你要保存的路径
//                                                  return [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
//                                              }completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
//                                              {
//                                                  if(filePath==nil)
//                                                  {
//                                                      //图片地址空
//                                                      NSLog(@"图片地址空,request:%@",request);
//                                                      NSLog(@"error:%@",error);
//                                                  }
//                                                  else
//                                                  {
//                                                      NSLog(@"File downloaded to: %@", filePath);
//                                                  }
//                                              }];
//    [downloadTask resume];
}
-(void)btnClick:(UIButton *)sender
{
    if (_navigationBarState==1) {
        self.navigationController.navigationBar.hidden=NO;
    }else{
        self.navigationController.navigationBar.hidden=YES;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)downLoadImage
{
    NSString *urlStr=_imageArrays[_currentIndex];
    urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]];
    [self saveImageToPhotos:image];
}
- (void)saveImageToPhotos:(UIImage*)image
{
    
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    
}

// 指定回调方法

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo

{
    
    NSString *msg = nil ;
    
    if(error != NULL){
        
        msg = @"保存图片失败" ;
        
    }else{
        
        msg = @"保存图片成功" ;
        
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                          
                                                    message:msg
                          
                                                   delegate:self
                        
                                          cancelButtonTitle:@"确定"
            
                                          otherButtonTitles:nil];
    [alert show];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=NO;
}

@end
